package com.yenlien.traceyun.control.service;


import com.yenlien.traceyun.control.dao.BirthDao;
import com.yenlien.traceyun.control.entity.Birth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LiuSha on 2020/8/7.
 */
@Service
public class BirthService {
    @Autowired
    private BirthDao birthDao;

    @Transactional(rollbackFor = RuntimeException.class)
    public void saves(List<Birth> birthList, String modelId) throws Exception {
        List<Birth> births = findByModelId(modelId);
        List<String> deleteIds = new ArrayList<>();
        if (births.size() > 0) {
            deleteIds = births.stream().map(p -> p.getId()).collect(Collectors.toList());
        }
        for (Birth birth : birthList) {
            birth.setModelId(modelId);
            birthDao.save(birth);
            if (deleteIds.size() > 0 && deleteIds.contains(birth.getId())) {
                deleteIds.remove(birth.getId());
            }
        }
        deletes(deleteIds);
    }

    public List<Birth> findByModelId(String modelId) {
        return birthDao.findByModelId(modelId);
    }

    public void deletes(List<String> ids) {
        for (String id : ids) {
            birthDao.deleteById(id);
        }
    }

}
